package com.alphacsp.theedge2012.ui.activities;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.ViewFlipper;
import com.alphacsp.theedge2012.R;
import com.alphacsp.theedge2012.data.adapters.SessionsAdapter;
import com.alphacsp.theedge2012.data.database.DataAccessor;
import com.alphacsp.theedge2012.data.entities.Session;
import com.alphacsp.theedge2012.data.entities.Speaker;
import com.alphacsp.theedge2012.data.service.NetworkService;
import com.alphacsp.theedge2012.data.service.NetworkServiceHelper;
import com.alphacsp.theedge2012.data.service.ServiceListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Gilad
 * Date: 23/10/10
 * Time: 00:53
 */
public class SessionsActivity extends ListActivity implements ServiceListener {

    private SessionsAdapter sessionsAdapter;
    private DataAccessor dataAccessor;
    private NetworkServiceHelper networkServiceHelper;
    private List<Session> sessions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final String query = getIntent().getStringExtra(SearchManager.QUERY);
        final String speakerName = getIntent().getStringExtra("speakerName");
        final String parallelQuery = getIntent().getStringExtra("parallelQuery");

        sessions = new ArrayList<Session>();
        networkServiceHelper = new NetworkServiceHelper(this);

        dataAccessor = DataAccessor.getSingleton(this);

        if (query != null && query.length() > 0) {
            if (!sessions.isEmpty()) {
                sessions.clear();
            }
            sessions = dataAccessor.searchSessions(query);
            setContentView(R.layout.sessions_activity_bare);
            sessionsAdapter = new SessionsAdapter(this, R.layout.sessions_activity, sessions);
            setListAdapter(sessionsAdapter);
        } else if (speakerName != null && speakerName.length() > 0) {
            if (!sessions.isEmpty()) {
                sessions.clear();
            }
            sessions = dataAccessor.getSessionsBySpeaker(speakerName);
            setContentView(R.layout.sessions_activity_bare);
            sessionsAdapter = new SessionsAdapter(this, R.layout.sessions_activity, sessions);
            setListAdapter(sessionsAdapter);
        } else if (parallelQuery != null && parallelQuery.length() > 0) {
            if (!sessions.isEmpty()) {
                sessions.clear();
            }
            sessions = dataAccessor.getParallelSessions(parallelQuery);
            setContentView(R.layout.sessions_activity_bare);
            sessionsAdapter = new SessionsAdapter(this, R.layout.sessions_activity, sessions);
            setListAdapter(sessionsAdapter);
        } else {
            initSessions();
            final Intent serviceIntent = new Intent(Intent.ACTION_SYNC, null, this, NetworkService.class);
            serviceIntent.putExtra(NetworkService.STATUS_LISTENER, networkServiceHelper);
            serviceIntent.putExtra(NetworkService.REFRESH_ACTION, NetworkService.REFRESH_SESSIONS);
            startService(serviceIntent);
        }
        getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i > 0) {
                    for (int index = 0; i < absListView.getChildCount(); i++) {
                        final ViewFlipper child = (ViewFlipper) absListView.getChildAt(i);
                        if (child.getDisplayedChild() != 0) {
                            child.setDisplayedChild(0);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });

        getListView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if ((i == KeyEvent.KEYCODE_DPAD_DOWN  || i==KeyEvent.KEYCODE_DPAD_UP)&& keyEvent.getAction() == KeyEvent.ACTION_DOWN && view instanceof ListView) {
                    final ViewGroup group = (ViewGroup) view;
                    for (int index = 0; index < group.getChildCount(); index++) {
                        final ViewFlipper child = (ViewFlipper) group.getChildAt(index);
                        if (child != null && child.getDisplayedChild() != 0) {
                            child.setDisplayedChild(0);
                        }
                    }
                }
                return false;
            }
        });
    }


    private void initSessions() {
        setContentView(R.layout.sessions_activity);
        sessions = dataAccessor.getAllSessions();
        sessionsAdapter = new SessionsAdapter(this, R.layout.sessions_activity, sessions);
        setListAdapter(sessionsAdapter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dataAccessor.closeDatabase();
    }

    public void onHomeClick(View view) {
        final Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onReceiveResult(int resultCode, Bundle resultData) {
        if (resultCode == NetworkService.STATUS_REFRESHED) {
            initSessions();
        }
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void onSearchClick(View v) {
        onSearchRequested();
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void swipeProfileClickListener(View view) {
        final Session session = sessionsAdapter.getItem((Integer) view.getTag());

        final List<Speaker> speakers = dataAccessor.searchSpeakers(session.getPresenter());
        Speaker speaker = speakers.get(0);
        Intent intent = new Intent(SessionsActivity.this, SpeakerDetailsActivity.class);
        intent.putExtra("speakerName", speaker.getName());
        intent.putExtra("speakerCompany", speaker.getCompany());
        intent.putExtra("speakerBio", speaker.getBio());
        intent.putExtra("speakerImageUrl", speaker.getImageUrl());
        startActivity(intent);
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void swipeSessionClickListener(View view) {
        final Session session = sessionsAdapter.getItem((Integer) view.getTag());
        Intent intent = new Intent(SessionsActivity.this, SessionDetailsActivity.class);
        intent.putExtra("sessionTopic", session.getTopic());
        intent.putExtra("sessionPresenter", session.getPresenter());
        intent.putExtra("sessionAbstract", session.getSessionAbstract());
        startActivity(intent);
    }


}
